#include "acceptor.h"
#include "channel.h"
#include "socket.h"
#include <cassert>
#include <fcntl.h>
#include <utility>

Acceptor::Acceptor(EventLoop *loop, int port) {
    socket_ = std::make_unique<Socket>();
    assert(socket_->create() == RC_SUCCESS);
    assert(socket_->bind(Socket::getLocalIP("eth0"), port) == RC_SUCCESS);
    assert(socket_->listen() == RC_SUCCESS);

    channel_ = std::make_unique<Channel>(socket_->fd(), loop);
    std::function<void()> cb = std::bind(&Acceptor::AcceptConnection, this);

    channel_->set_read_callback(cb);
    channel_->EnableRead();
}

Acceptor::~Acceptor() {}

RC Acceptor::AcceptConnection() const {
    int clnt_fd = -1;
    if (socket_->accept(clnt_fd) != RC_SUCCESS) {
        return RC_ACCEPTOR_ERROR;
    }
    fcntl(clnt_fd, F_SETFL, fcntl(clnt_fd, F_GETFL) | O_NONBLOCK); // 新连接设置为非阻塞式
    if (new_connection_callback_) {
        new_connection_callback_(clnt_fd);
    }
    return RC_SUCCESS;
}

void Acceptor::set_new_connection_callback(std::function<void(int)> const &callback) {
    new_connection_callback_ = std::move(callback);
}
